//
//  ExchangeController.m
//  YiBaoStore
//
//  Created by 毛云河 on 2019/1/5.
//  Copyright © 2019 小河. All rights reserved.
//

#import "ExchangeController.h"
#import "ExchangeCell.h"

@interface ExchangeController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UISwitch *mySwich;
@property (nonatomic, assign) BOOL isOpen;

@property (nonatomic, strong) MYHAleartView *aleartView;

@end

@implementation ExchangeController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setNav];
    [self createTableView];
    [self httpSwichStatue];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.dataArray = [NSMutableArray array];
    [self httpRequestActivityGoodList];
}

#pragma mark - 获取活动状态
- (void)httpSwichStatue
{
    __weak ExchangeController *myself = self;
    [HttpRequest formPostPath:GetActivityState_API params:nil resultBlock:^(id Data, MsgModel *msgModel)
    {
        if (msgModel.status == 200)
        {
            
            
        }
    }];
}

- (void)httpRequestActivityGoodList
{
    __weak ExchangeController *myself = self;
    [HttpRequest formPostPath:ActivityGoodsList_API params:nil resultBlock:^(NSDictionary *Data, MsgModel *msgModel)
     {
         NSError *error;
         if (msgModel.status == 200)
         {
             NSDictionary *attributes = Data[@"attributes"];
             NSString *increasePurchaseState = [NSString stringWithFormat:@"%@",(NSString *)attributes[@"increasePurchaseState"]];
             NSLog(@"活动商品状态***%@",increasePurchaseState);
             if ([increasePurchaseState isEqualToString:@"0"])
             {
                 myself.isOpen = NO;
             }else {
                 myself.isOpen = YES;
             }
             NSArray *result = Data[@"result"];
             for (NSDictionary *dic in result)
             {
                 MainModel *model = [[MainModel alloc] initWithDictionary:dic error:&error];
                 [myself.dataArray addObject:model];
             }
             [myself.myTableView reloadData];
             myself.myTableView.tableHeaderView = [myself tableHeaderView];
             [myself.myTableView.mj_header endRefreshing];
         }else {
             [myself.myTableView.mj_header endRefreshing];
             [myself.myTableView.mj_footer endRefreshingWithNoMoreData];
         }
     }];
}


#pragma mark - 设置导航
- (void)setNav
{
    self.titLabel.text = @"超值换购";
    UIView *lineView = [[UIView alloc] init];
    [self.view addSubview:lineView];
    lineView.frame = CGRectMake(0, self.bgNavView.bottom, SCREENWIDTH, 1);
    lineView.backgroundColor = RGBACOLOR(241, 241, 241, 1);
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.bgNavView addSubview:rightBtn];
    rightBtn.titleLabel.font = FontWithSize(18);
    rightBtn.frame = CGRectMake(SCREENWIDTH-72-15, self.bgNavView.bottom-20-10, 72, 18);
    [rightBtn setTitle:@"选择商品" forState:UIControlStateNormal];
    [rightBtn setTitleColor:RGBACOLOR(74, 144, 226, 1) forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)rightBtnClick:(UIButton *)sender
{
    SelectGoodsController *select = [[SelectGoodsController alloc] init];
    [self.navigationController pushViewController:select animated:YES];
}

- (void)createTableView
{
    if (@available(iOS 11.0, *))
    {
        self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.bgNavView.bottom+1, SCREENWIDTH, SCREENHEIGHT-self.bgNavView.bottom-1-BottomHeight_xs) style:UITableViewStylePlain];
    }
    else {
        self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.bgNavView.bottom+1, SCREENWIDTH, SCREENHEIGHT-self.bgNavView.bottom-1-BottomHeight) style:UITableViewStylePlain];
    }
    self.myTableView.backgroundColor = RGBACOLOR(241, 241, 241, 1);
    [self.view addSubview:self.myTableView];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.sectionHeaderHeight = 0.01f;
    self.myTableView.sectionFooterHeight = 10.f;
    
    self.myTableView.tableFooterView = [UIView new];
    
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(httpRequestNewData)];
//    self.myTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(httpMoreData)];
    
    [TTKUtil setAutomaticallyAdjustsScrollViewInsetsWidth:self.myTableView withView:self];
    [self.myTableView registerClass:[ExchangeCell class] forCellReuseIdentifier:@"ExchangeCell"];
}

- (void)httpRequestNewData
{
    [self.dataArray removeAllObjects];
    [self httpRequestActivityGoodList];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    [self.myTableView tableViewDisplayWitMsg:@"您还没有任何活动商品，赶紧去采购吧" ifNecessaryForRowCount:self.dataArray.count withBottonTitle:@"选择商品"];
    __weak ExchangeController *myself = self;
    self.myTableView.myBlcok = ^(int index)
    {
        NSLog(@"选择商品");
        SelectGoodsController *select = [[SelectGoodsController alloc] init];
        [myself.navigationController pushViewController:select animated:YES];
    };
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 153.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ExchangeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExchangeCell"];
    
    cell.stickBtn.indexPath = indexPath;
    cell.editBtn.indexPath = indexPath;
    cell.deleteBtn.indexPath = indexPath;
    
    [cell.stickBtn addTarget:self action:@selector(stickBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.editBtn addTarget:self action:@selector(editBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    MainModel *model = self.dataArray[indexPath.row];
    [cell setCellWithMode:model];
    
    return cell;
}

#pragma mark - 置顶按钮点击事件
- (void)stickBtnClick:(UIButton *)sender
{
    MainModel *model = self.dataArray[sender.indexPath.row];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:model.product_id forKey:@"itemId"];//商品id
    __weak ExchangeController *myself = self;
    [HttpRequest formPostPath:StickyActivity_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
     {
         if (msgModel.status == 200)
         {
             [myself httpRequestNewData];
             [myself.myTableView reloadData];
         }
     }];
}

#pragma mark - 编辑按钮点击事件
- (void)editBtnClick:(UIButton *)sender
{
    MainModel *model = self.dataArray[sender.indexPath.row];
    self.aleartView = [[MYHAleartView alloc] initActivityWithModel:model isExChange:1];
    [self.aleartView showAlertView];
    __weak ExchangeController *myself = self;
    self.aleartView.ActivityGoddsBlock = ^(NSString * _Nonnull promotionPrice, NSString * _Nonnull stock)
    {
        NSLog(@"确认添加");
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:model.product_id forKey:@"itemId"];
        [dic setValue:promotionPrice forKey:@"promotionPrice"];
        [dic setValue:stock forKey:@"stock"];
        [HttpRequest formPostPath:AddActivityGoods_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
         {
             if (msgModel.status == 200)
             {
                 NSLog(@"编辑活动成功");
                 [myself.aleartView removeFromSuperview];
                 [myself httpRequestNewData];
             }
         }];
        
    };
    
}

#pragma mark - 删除按钮点击事件
- (void)deleteBtnClick:(UIButton *)sender
{
    MainModel *model = self.dataArray[sender.indexPath.row];
    MYHAleartView *alertView = [[MYHAleartView alloc] initMecommendAlertViewWithMessage:@"确认要删除该商品吗？" fuText:@"删除后，该商品在加价购活动下架" sureBtnTitle:@"确认" cancleBtnTitle:@"取消"];
    [alertView showAlertView];
    alertView.sureBlock = ^(id  _Nonnull sender)
    {
        NSLog(@"确认删除");
        [self removeGoodsWithItemId:model.product_id];
    };
}

#pragma mark - 删除商品
- (void)removeGoodsWithItemId:(NSString *)itemId
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:itemId forKey:@"itemId"];//商品id
    __weak ExchangeController *myself = self;
    [HttpRequest formPostPath:RemoveActivityGoods_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
     {
         if (msgModel.status == 200)
         {
             [myself httpRequestNewData];
             [myself.myTableView reloadData];
         }
     }];
}

- (UIView *)tableHeaderView
{
    UIView *headerView = [[UIView alloc] init];
    if (self.dataArray.count>0)
    {
        headerView.backgroundColor = [UIColor whiteColor];
        headerView.frame = CGRectMake(0, 0, SCREENWIDTH, 54);
        
        UIView *line = [[UIView alloc] init];
        [headerView addSubview:line];
        line.backgroundColor = RGBACOLOR(241, 241, 241, 1);
        line.frame = CGRectMake(0, headerView.height-1, SCREENWIDTH, 1);
        
        UILabel *label = [[UILabel alloc] init];
        [headerView addSubview:label];
        label.frame = CGRectMake(15, (headerView.height-20)/2, 90, 20);
        label.font = FontWithSize(14);
        label.text = @"是否开启活动";
        label.textAlignment = 0;
        label.textColor = RGBACOLOR(17, 17, 15, 1);
        
        self.mySwich = [[UISwitch alloc] init];
        [headerView addSubview:self.mySwich];
        [self.mySwich setOn:self.isOpen];
        self.mySwich.frame = CGRectMake(label.right+10, (54-31)/2, 40, 31);
        self.mySwich.onTintColor= RGBACOLOR(239, 208, 83, 1);
        [self.mySwich addTarget:self action:@selector(changeStatue:) forControlEvents:UIControlEventValueChanged];
    }
    
    return headerView;
}

#pragma mark - 是否开启活动
- (void)changeStatue:(UISwitch *)sender
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (self.isOpen)
    {
        [dic setValue:@"0" forKey:@"increasePurchaseState"];
    }
    else {
        [dic setValue:@"1" forKey:@"increasePurchaseState"];
    }
    
    __weak ExchangeController *myself = self;
    [HttpRequest formPostPath:ActivitySwitch_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
    {
        if (msgModel.status == 200)
        {
            myself.isOpen = !myself.isOpen;
            [myself.mySwich setOn:myself.isOpen];
        }
    }];
}


@end
